package com.mtw.bbs.util;

import cn.hutool.core.collection.CollectionUtil;
import com.mtw.bbs.article.pojo.vo.ArticleVo;
import com.mtw.bbs.article.service.ArticleFileService;
import com.mtw.bbs.common.core.constant.BusinessObjectType;
import com.mtw.bbs.common.core.security.UserDetails;
import com.mtw.bbs.common.core.security.context.SecurityContextHolder;
import com.mtw.bbs.common.core.vo.BaseFileVo;
import com.mtw.bbs.article.pojo.vo.LikeCountVo;
import com.mtw.bbs.like.service.LikeProviderService;
import com.mtw.bbs.article.pojo.vo.ReplyCountVo;
import com.mtw.bbs.reply.service.ReplyProviderService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Component
@RequiredArgsConstructor
public class ArticleComponent {


    private final ThreadPoolTaskExecutor bizExecutor;
    private final ArticleFileService articleFileService;
    private final LikeProviderService likeProviderService;
    private final ReplyProviderService replyProviderService;


    /**
     * 设置点赞数、话题等信息
     */
    public void setArticleSubject(List<ArticleVo> voList, String userId) {

        List<String> ids = voList.stream().map(ArticleVo::getId).toList();
        Map<String, LikeCountVo> likedMap = null;
        Map<String, Integer> replyMap = null;

        // 点赞信息
        CompletableFuture<Map<String, LikeCountVo>> likeF = CompletableFuture.supplyAsync(() -> {
            List<LikeCountVo> likeResult = likeProviderService.getLikedListWithCount(BusinessObjectType.ARTICLE, ids, userId);
            if (CollectionUtil.isNotEmpty(likeResult)) {
                return likeResult.stream().collect(Collectors.toMap(LikeCountVo::getObjectId, Function.identity(), (v1, v2) -> v1));
            }
            return null;
        }, bizExecutor);


        // 评论信息
        CompletableFuture<Map<String, Integer>> replyF = CompletableFuture.supplyAsync(() -> {
            List<ReplyCountVo> replyResult = replyProviderService.getCountByBusAndMessageIds(BusinessObjectType.ARTICLE, ids);
            if (CollectionUtil.isNotEmpty(replyResult)) {
                return replyResult.stream().collect(Collectors.toMap(ReplyCountVo::getObjectId, ReplyCountVo::getCount, (v1, v2) -> v1));
            }
            return null;
        }, bizExecutor);


        long s = System.currentTimeMillis();
        // 查附件
        Map<String, List<BaseFileVo>> fileMap = articleFileService.getFileMap(ids);
        log.info("查询附件耗时：{}ms", System.currentTimeMillis() - s);

        try {
            likedMap = likeF.get(5, TimeUnit.SECONDS);
            replyMap = replyF.get(5, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("获取点赞、评论信息异常", e);
        }finally {
            if (CollectionUtil.isEmpty(likedMap)){
                likedMap = new HashMap<>();
            }
            if (CollectionUtil.isEmpty(replyMap)){
                replyMap = new HashMap<>();
            }
        }

        for (ArticleVo x : voList) {
            //点赞
            LikeCountVo likeVo = likedMap.get(x.getId());
            if (likeVo != null) {
                x.setLikeOrDis(likeVo.getLikeStatus());
                x.setLikeCount(likeVo.getCount());
            }
            // 评论
            Integer replyCount = replyMap.get(x.getId());
            x.setReplyCount(replyCount == null ? 0 : replyCount);
            // 附件
            x.setFileList(fileMap.get(x.getId()));
        }
    }


    /**
     * 获取文章评论数量
     */
    public Integer getArticleReplyCount(String id) {
        // 设置评论总数
        ReplyCountVo replyResult = replyProviderService.getCountByBusAndMessageId(BusinessObjectType.ARTICLE, id);
        if (replyResult != null) {
            return replyResult.getCount();
        }
        return 0;
    }


    /**
     * 获取文章点赞信息
     */
    public LikeCountVo getArticleLikeInfo(String id) {

        UserDetails user = SecurityContextHolder.getContext().getAuthentication();
        return likeProviderService.getLikedWithCount(BusinessObjectType.ARTICLE, id, user != null ? user.getId() : null);
    }


}
